package org.carabiner.infinitest;

import java.awt.Color;
import java.awt.Component;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;

public class FailureCellRenderer extends DefaultTreeCellRenderer
{  
  private static final Color FAILURE_COLOR = Color.RED;
  private static final Color ERROR_COLOR = new Color(0xb22222);
  private Icon errorIcon;
  private Icon failureIcon;

  public FailureCellRenderer()
  {    
    errorIcon = new ImageIcon(FailureCellRenderer.class.getResource("error.png"));
    failureIcon = new ImageIcon(FailureCellRenderer.class.getResource("failure.png"));
  }
  
  public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus)
  {
    JLabel label = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
        row, hasFocus);
    
    if (value instanceof InfinitestTreeNode)
    {
      InfinitestTreeNode node = (InfinitestTreeNode) value;
      if (node.isLeaf())
      {
        updateColorAndIcon(label, node);
      }
      else
      {
        label.setIcon(null);
      }
    }
    return label;
  }

  private void updateColorAndIcon(JLabel label, InfinitestTreeNode node)
  {
    if (node.getTestEvent().isFailure())
    {
      label.setForeground(FAILURE_COLOR);
      label.setIcon(failureIcon);
    }
    else
    {
      label.setForeground(ERROR_COLOR);
      label.setIcon(errorIcon);
    }
  }

}
